package com.party.mobile.biz.member;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.party.authorization.manager.impl.RedisTokenManager;
import com.party.common.constant.Constant;
import com.party.common.utils.PartyCode;
import com.party.common.utils.PasswordUtils;
import com.party.common.utils.StringUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.AuditStatus;
import com.party.core.model.YesNoStatus;
import com.party.core.model.member.Member;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.system.MemberSysRole;
import com.party.core.model.system.RoleEnum;
import com.party.core.model.system.RoleType;
import com.party.core.model.system.SysRole;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.member.IMemberService;
import com.party.core.service.system.IMemberSysRoleService;
import com.party.core.service.system.ISysConfigService;
import com.party.core.service.system.ISysRoleService;
import com.party.mobile.biz.copartner.CopartnerRoleBizService;
import com.party.mobile.biz.currentUser.CurrentUserBizService;
import com.party.mobile.web.dto.copartner.input.CeoRegisterInput;
import com.party.mobile.web.dto.copartner.input.CopartnerRegisterInput;
import com.party.mobile.web.dto.login.input.LoginInput;
import com.party.mobile.web.dto.login.input.VerifyCodeLoginInput;
import com.party.mobile.web.dto.login.output.CurrentUser;
import com.party.mobile.web.dto.login.output.MemberOutput;
import com.party.mobile.web.dto.member.input.PasswordSetInput;
import com.party.notify.notifyPush.officialPartner.ICopartnerNotifySendService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @ClassName CopartnerMemberBizService
 * @Description CEO户外联盟member业务处理
 * @Author yifeng
 * @Date 2019/9/29 17:30
 **/
@Service
public class CopartnerMemberBizService {
    @Autowired
    private IMemberGroupService memberGroupService;
    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private MemberBizService memberBizService;
    @Autowired
    private IMemberSysRoleService memberSysRoleService;
    @Autowired
    private CopartnerRoleBizService copartnerRoleBizService;
    @Autowired
    private IMemberService memberService;
    @Autowired
    private ICopartnerNotifySendService copartnerNotifySendService;
    @Autowired
    private RedisTokenManager redisTokenManager;
    @Autowired
    private CurrentUserBizService currentUserBizService;

    private String isCopartner = "isCopartner";
    private String isChannelDis = "isChannelDis";
    private String isCosponsor = "isCosponsor";

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 注册合作机构注册
     *
     * @param input 输入参数
     * @return 会员输出视图
     */
    public MemberOutput register(CopartnerRegisterInput input) {

        //验证手机号是否存在
        MemberGroup dbMember = memberGroupService.findByPhone(input.getMobile(), Constant.MEMBER_ORGANIZATION);
        if (null != dbMember) {
            throw new BusinessException(PartyCode.PHONE_EXIST, "手机号码已经注册");
        }

        // 加短信开关
        boolean needVerify = sysConfigService.isVerifySms();
        if (needVerify) {
            // 验证验证码
            boolean isVerify = memberBizService.verifyCode(input.getMobile(), input.getVerifyCode(), input.getCountryCode());
            if (!isVerify) {
                throw new BusinessException(PartyCode.VERIFY_CODE_ERROR, "手机验证码不一致");
            }
        }

        MemberGroup memberGroup = createMemberGroup(Constant.MEMBER_ORGANIZATION);

        memberGroup.setMobile(input.getMobile());
        memberGroup.setPassword(PasswordUtils.encryptPassword(Constant.DEFALT_PASSWORD));
        memberGroup.setCompany(input.getCompany());
        memberGroup.setCity(input.getCity());
        memberGroup.setIndustry(input.getIndustry());
        memberGroup.setLogo(input.getLogo());
        memberGroup.setRealname(input.getCompany());
        if (StringUtils.isNotEmpty(input.getCountryCode())) {
            memberGroup.setCountryCode(input.getCountryCode());
        }
        memberGroupService.update(memberGroup);

        //设置角色
        SysRole sysRole = new SysRole();
        sysRole.setCode(RoleEnum.COPARTNER_ROLE.getCode());
        sysRole.setType(RoleType.SYSTEM_ROLE.getCode());
        SysRole copartner = sysRoleService.uniqueProperty(sysRole);
        MemberSysRole memberSysRole = new MemberSysRole(memberGroup.getId(), copartner.getId());
        memberSysRoleService.insert(memberSysRole);

        MemberOutput memberOutput = MemberOutput.transform(memberGroup);
        String token = memberBizService.getToken(memberGroup, null);
        memberOutput.setToken(token);
        return memberOutput;
    }

    /**
     * 注册合作机构注册
     *
     * @param input 输入参数
     * @return 会员输出视图
     */
    public MemberOutput registerV2(CopartnerRegisterInput input) {
        MemberOutput memberOutput = verifyMemberRegister(input.getMobile(), input.getVerifyCode(),
                input.getCountryCode(), input.getInviteCode(), null);
        if (null != memberOutput) {
            return memberOutput;
        }

        Member member = memberBizService.createMember(Constant.MEMBER_PERSONAL);
        //给新的用户初始化角色和上下级关系
        copartnerRoleBizService.initializingRole(member, input.getInviteCode());

        member.setMobile(input.getMobile());
        member.setCompany(input.getCompany());
        member.setCity(input.getCity());
        member.setIndustry(input.getIndustry());
        member.setWantRes(input.getWantRes());
        member.setLogo(input.getLogo());
        member.setRealname(input.getRealname());
        if (StringUtils.isNotEmpty(input.getCountryCode())) {
            member.setCountryCode(input.getCountryCode());
        }
        memberService.update(member);

        try {
            if (StringUtils.isNotEmpty(input.getInviteCode())) {
                Member inviteMember = memberService.findByPhone(input.getInviteCode(), Constant.MEMBER_PERSONAL);
                copartnerNotifySendService.sendRegisterSuccess(inviteMember.getId(), member.getRealname());
            }
        } catch (Exception e) {
            logger.error("合伙人注册消息推送异常", e);
        }
        memberOutput = MemberOutput.transform(member);
        String token = memberBizService.getToken(member);
        memberOutput.setToken(token);
        return memberOutput;
    }

    /**
     * ceo户外联盟注册
     *
     * @param input 输入参数
     * @return 用户实体
     */
    public MemberOutput registerV3(CeoRegisterInput input) {
        MemberOutput memberOutput = verifyMemberRegister(input.getPhone(), input.getVerifyCode(),
                input.getCountryCode(), input.getInviteCode(), input.getPassword());
        if (null != memberOutput) {
            return memberOutput;
        }

        Member member = memberBizService.createMember(Constant.MEMBER_PERSONAL);
        //给新的用户初始化角色和上下级关系
        copartnerRoleBizService.initializingRole(member, input.getInviteCode());

        member.setMobile(input.getPhone());
        member.setPassword(PasswordUtils.encryptPassword(input.getPassword()));
        if (StringUtils.isNotEmpty(input.getCountryCode())) {
            member.setCountryCode(input.getCountryCode());
        }
        memberService.update(member);


        memberOutput = MemberOutput.transform(member);
        String token = memberBizService.getToken(member);
        memberOutput.setToken(token);
        return memberOutput;
    }

    /**
     * 创建会员，并初始化
     *
     * @return 会员实体
     */
    @Transactional
    public MemberGroup createMemberGroup(Integer type) {
        MemberGroup memberGroup = new MemberGroup();
        // 合作商
        memberGroup.setIsPartner(YesNoStatus.NO.getCode());
        // 管理员
        memberGroup.setIsAdmin(YesNoStatus.NO.getCode());
        // 合作渠道
        memberGroup.setIsCosponsor(YesNoStatus.NO.getCode());
        memberGroup.setPassword(PasswordUtils.encryptPassword(Constant.DEFALT_PASSWORD));
        memberGroup.setType(type);
        memberGroupService.insert(memberGroup);//保存会员
        return memberGroup;
    }

    /**
     * 验证用户注册
     *
     * @param phone       手机号
     * @param verifyCode  短信验证码
     * @param countryCode 国际号
     * @param inviteCode  邀请码
     */
    public MemberOutput verifyMemberRegister(String phone, String verifyCode, String countryCode, String inviteCode, String password) {
        // 加短信开关
        boolean needVerify = sysConfigService.isVerifySms();
        if (needVerify) {
            // 验证验证码
            boolean isVerify = memberBizService.verifyCode(phone, verifyCode, countryCode);
            if (!isVerify) {
                throw new BusinessException(PartyCode.VERIFY_CODE_ERROR, "手机验证码不一致");
            }
        }

        //验证手机号是否存在
        Member dbMember = memberService.findByPhone(phone, Constant.MEMBER_PERSONAL);
        if (null != dbMember) {
            if (!copartnerRoleBizService.initializingRole(dbMember, inviteCode)) {
                throw new BusinessException(PartyCode.PHONE_EXIST, "手机号码已经注册");
            }
            if (StringUtils.isNotEmpty(password)) {
                dbMember.setPassword(PasswordUtils.encryptPassword(password));
                memberService.update(dbMember);
            }
            MemberOutput memberOutput = MemberOutput.transform(dbMember);
            return memberOutput;
        }
        return null;
    }

    /**
     * ceo户外联盟验证码登录
     *
     * @param input 登陆参数
     * @return 用户实体
     */
    public MemberOutput copartnerVerifyLoginV2(VerifyCodeLoginInput input, String identityName) {
        MemberOutput memberOutput = null;
        // 加短信开关
        boolean needVerify = sysConfigService.isVerifySms();
        if (needVerify) {
            // 验证验证码
            boolean isVerify = memberBizService.verifyCode(input.getPhone(), input.getVerifyCode(), input.getCountryCode());
            if (!isVerify) {
                throw new BusinessException(PartyCode.VERIFY_CODE_ERROR, "手机验证码不一致");
            }
        }

        boolean isExists = true;
        Member member = null;
        MemberGroup memberGroup = null;
        String memberId = null;

        // 个人身份的
        Member perMember = memberService.findByPhone(input.getPhone(), Constant.MEMBER_PERSONAL);
        // 机构身份
        MemberGroup orgMember = memberGroupService.findByPhone(input.getPhone(), Constant.MEMBER_ORGANIZATION);

        if (null != perMember || null != orgMember) {
            if (StringUtils.isEmpty(identityName)) {
                throw new BusinessException(PartyCode.MEMBER_UNEXIST, "身份不能为空");
            }
            if (isCopartner.equals(identityName) || isChannelDis.equals(identityName)) {
                member = perMember;
            } else if (isCosponsor.equals(identityName)) {
                memberGroup = orgMember;
            }
        }

        if (null == member && null == memberGroup) {
            isExists = false;
        } else {
            if (null != member) {
                memberOutput = memberBizService.getLoginMember(member);
                memberId = member.getId();
            } else if (null != memberGroup) {
                memberOutput = memberBizService.getLoginMember(memberGroup);
                memberId = memberGroup.getId();
            }
            isExists = hasCopartnerRole(memberId, memberOutput, identityName);
        }
        // 只有身份为合伙人时，验证码登录不存在则注册新账号；另外两个身份不存在则抛出不存在的异常
        if ((isCopartner.equals(identityName) || isCosponsor.equals(identityName)) && !isExists) {
            throw new BusinessException(PartyCode.MEMBER_UNEXIST, "账号不存在");
        }

        if (!isExists) {
            CopartnerRegisterInput registerInput = new CopartnerRegisterInput();
            registerInput.setMobile(input.getPhone());
            registerInput.setVerifyCode(input.getVerifyCode());
            registerInput.setCountryCode(input.getCountryCode());
            memberOutput = registerV2(registerInput);
            hasCopartnerRole(memberOutput.getRegistrationId(), memberOutput);
        }
        return memberOutput;
    }

    /**
     * ceo户外联盟验证码登录
     *
     * @param input 登陆参数
     * @return 用户实体
     */
    public MemberOutput copartnerVerifyLogin(VerifyCodeLoginInput input) {
        MemberOutput memberOutput = null;
        // 加短信开关
        boolean needVerify = sysConfigService.isVerifySms();
        if (needVerify) {
            // 验证验证码
            boolean isVerify = memberBizService.verifyCode(input.getPhone(), input.getVerifyCode(), input.getCountryCode());
            if (!isVerify) {
                throw new BusinessException(PartyCode.VERIFY_CODE_ERROR, "手机验证码不一致");
            }
        }

        boolean isExists = true;

        //查找用户
        Member member = memberService.findByLoginNameOld(input.getPhone(), false);
        if (null == member) {
            isExists = false;
        } else {
            memberOutput = memberBizService.getLoginMember(member);
            isExists = hasCopartnerRole(member.getId(), memberOutput);
        }

        if (!isExists) {
            CopartnerRegisterInput registerInput = new CopartnerRegisterInput();
            registerInput.setMobile(input.getPhone());
            registerInput.setVerifyCode(input.getVerifyCode());
            registerInput.setCountryCode(input.getCountryCode());
            memberOutput = registerV2(registerInput);
            hasCopartnerRole(memberOutput.getRegistrationId(), memberOutput);
        }
        return memberOutput;
    }

    /**
     * ceo户外联盟账号密码登陆
     *
     * @param loginInput 登陆参数
     * @return 用户实体
     */
    public MemberOutput copartnerPwdLoginV2(LoginInput loginInput, String identityName) {
        String memberId = null;
        String password = null;
        MemberOutput memberOutput = null;
        Member member = null;
        MemberGroup memberGroup = null;
        boolean number = NumberUtils.isNumber(loginInput.getUsername());
        if (number) {
            // 如果是数字，就认为是手机号
            // 个人身份的
            Member perMember = memberService.findByPhone(loginInput.getUsername(), Constant.MEMBER_PERSONAL);
            // 机构身份
            MemberGroup orgMember = memberGroupService.findByPhone(loginInput.getUsername(), Constant.MEMBER_ORGANIZATION);
            List<Map<String, Object>> identities = getMemberIdentities(perMember, orgMember);
            if (CollectionUtils.isEmpty(identities)) {
                throw new BusinessException(PartyCode.MEMBER_UNEXIST, "账号不存在");
            }
            if (isCopartner.equals(identityName) || isChannelDis.equals(identityName)) {
                member = perMember;
            } else if (isCosponsor.equals(identityName)) {
                memberGroup = orgMember;
            }
        } else {
            if (isCopartner.equals(identityName) || isChannelDis.equals(identityName)) {
                // 如果不是数字，就认为是用户名
                member = memberService.findByUserName(loginInput.getUsername());
            } else if (isCosponsor.equals(identityName)) {
                memberGroup = memberGroupService.findByUserName(loginInput.getUsername());
            }
        }

        if (null == member && null == memberGroup) {
            throw new BusinessException(PartyCode.MEMBER_UNEXIST, "用户不存在");
        }
        if (null != member) {
            password = member.getPassword();
        } else if (null != memberGroup) {
            password = memberGroup.getPassword();
        }

        boolean validate = PasswordUtils.validatePassword(loginInput.getPassword(), password);
        //验证凭证
        if (!validate) {
            throw new BusinessException(PartyCode.PASSWORD_UNMATCH, "用户名密码不匹配");
        }

        if (null != member) {
            memberOutput = memberBizService.getLoginMember(member);
            memberId = member.getId();
        } else if (null != memberGroup) {
            memberOutput = memberBizService.getLoginMember(memberGroup);
            memberId = memberGroup.getId();
        }

        boolean hasRole = hasCopartnerRole(memberId, memberOutput, identityName);
        if (!hasRole) {
            throw new BusinessException(PartyCode.ROLE_NOT_MATCH, "账号不存在");
        }
        return memberOutput;
    }

    /**
     * ceo户外联盟账号密码登陆
     *
     * @param loginInput 登陆参数
     * @return 用户实体
     */
    public MemberOutput copartnerPasswordLogin(LoginInput loginInput) {
        //查找用户
        Member member = memberService.findByLoginNameOld(loginInput.getUsername(), true);
        if (null == member) {
            throw new BusinessException(PartyCode.MEMBER_UNEXIST, "用户不存在");
        }

        boolean validate = PasswordUtils.validatePassword(loginInput.getPassword(), member.getPassword());
        //验证凭证
        if (!validate) {
            throw new BusinessException(PartyCode.PASSWORD_UNMATCH, "用户名密码不匹配");
        }

        MemberOutput memberOutput = memberBizService.getLoginMember(member);
        boolean hasRole = hasCopartnerRole(member.getId(), memberOutput);
        if (!hasRole) {
            throw new BusinessException(PartyCode.ROLE_NOT_MATCH, "账号不存在");
        }
        return memberOutput;
    }

    /**
     * 是否用户ceo户外联盟可登陆的角色
     *
     * @param memberId     用户id
     * @param memberOutput 渲染的实体
     * @return 结果 true/false
     */
    public boolean hasCopartnerRole(String memberId, MemberOutput memberOutput, Integer type) {
        boolean hasCopartner = false;
        boolean hasCosponsor = false;
        boolean hasChannelDis = false;
        boolean hasCopartnerDis = false;
        if (Constant.MEMBER_PERSONAL.equals(type)) {
            // 代言人
            hasCopartner = sysRoleService.hasRole(memberId, RoleEnum.COPARTNER_ROLE.getCode());
            // 渠道分销
            hasChannelDis = sysRoleService.hasRole(memberId, RoleEnum.CHANNEL_DISTRIBUTOR_ROLE.getCode());
            // 合伙人分销商
            hasCopartnerDis = sysRoleService.hasRole(memberId, RoleEnum.COPARTNER_DISTRIBUTOR_ROLE.getCode());
        } else {
            // 合作渠道
            hasCosponsor = sysRoleService.hasRole(memberId, RoleEnum.COSPONSOR_ROLE.getCode());
        }

        if (!(hasCopartner || hasCosponsor || hasChannelDis)) {
            return false;
        } else {
            if (hasChannelDis) {
                memberOutput.setIsChannelDis(YesNoStatus.YES.getCode());
            }
            if (hasCopartner) {
                memberOutput.setIsCopartner(YesNoStatus.YES.getCode());
            }
            if (hasCosponsor) {
                memberOutput.setIsCosponsor(YesNoStatus.YES.getCode());
            }
            if (hasCopartnerDis) {
                memberOutput.setIsCopartnerDis(YesNoStatus.YES.getCode());
            }
            return true;
        }
    }

    /**
     * 是否用户ceo户外联盟可登陆的角色
     *
     * @param memberId     用户id
     * @param memberOutput 渲染的实体
     * @return 结果 true/false
     */
    public boolean hasCopartnerRole(String memberId, MemberOutput memberOutput, String identityName) {
        boolean hasCopartner = false, hasCosponsor = false, hasChannelDis = false, hasCopartnerDis = false;
        if (isCopartner.equals(identityName)) {
            // 代言人
            hasCopartner = sysRoleService.hasRole(memberId, RoleEnum.COPARTNER_ROLE.getCode());
        } else if (isChannelDis.equals(identityName)) {
            // 渠道分销
            hasChannelDis = sysRoleService.hasRole(memberId, RoleEnum.CHANNEL_DISTRIBUTOR_ROLE.getCode());
            // 合伙人分销商
            hasCopartnerDis = sysRoleService.hasRole(memberId, RoleEnum.COPARTNER_DISTRIBUTOR_ROLE.getCode());
        } else if (isCosponsor.equals(identityName)) {
            // 合作渠道
            hasCosponsor = sysRoleService.hasRole(memberId, RoleEnum.COSPONSOR_ROLE.getCode());
        }
        if (!(hasCopartner || hasCosponsor || hasChannelDis)) {
            return false;
        } else {
            memberOutput.setIsChannelDis(hasChannelDis ? YesNoStatus.YES.getCode() : YesNoStatus.NO.getCode());
            memberOutput.setIsCopartner(hasCopartner ? YesNoStatus.YES.getCode() : YesNoStatus.NO_NEW.getCode());
            memberOutput.setIsCosponsor(hasCosponsor ? YesNoStatus.YES.getCode() : YesNoStatus.NO.getCode());
            memberOutput.setIsCopartnerDis(hasCopartnerDis ? YesNoStatus.YES.getCode() : YesNoStatus.NO.getCode());
            return true;
        }
    }

    /**
     * 是否用户ceo户外联盟可登陆的角色
     *
     * @param memberId     用户id
     * @param memberOutput 渲染的实体
     * @return 结果 true/false
     */
    public boolean hasCopartnerRole(String memberId, MemberOutput memberOutput) {
        // 代言人
        boolean hasCopartner = sysRoleService.hasRole(memberId, RoleEnum.COPARTNER_ROLE.getCode());
        // 合作渠道
        boolean hasCosponsor = sysRoleService.hasRole(memberId, RoleEnum.COSPONSOR_ROLE.getCode());
        // 渠道分销
        boolean hasChannelDis = sysRoleService.hasRole(memberId, RoleEnum.CHANNEL_DISTRIBUTOR_ROLE.getCode());
        // 合伙人分销商
        boolean hasCopartnerDis = sysRoleService.hasRole(memberId, RoleEnum.COPARTNER_DISTRIBUTOR_ROLE.getCode());
        if (!(hasCopartner || hasCosponsor || hasChannelDis)) {
            return false;
        } else {
            memberOutput.setIsChannelDis(hasChannelDis ? YesNoStatus.YES.getCode() : YesNoStatus.NO.getCode());
            memberOutput.setIsCopartner(hasCopartner ? YesNoStatus.YES.getCode() : YesNoStatus.NO_NEW.getCode());
            memberOutput.setIsCosponsor(hasCosponsor ? YesNoStatus.YES.getCode() : YesNoStatus.NO.getCode());
            memberOutput.setIsCopartnerDis(hasCopartnerDis ? YesNoStatus.YES.getCode() : YesNoStatus.NO.getCode());
            return true;
        }
    }


    /**
     * @param passwordSetInput 输入参数
     * @Author yifeng
     * @Description 重置密码
     * @Date 15:31 2019/5/15
     **/
    public void resetPassword(PasswordSetInput passwordSetInput, HttpServletRequest request) {
        //加短信开关
        boolean isNeedVerify = sysConfigService.isVerifySms();
        if (isNeedVerify) {
            // 验证验证码
            boolean isVerify = memberBizService.verifyCode(passwordSetInput.getPhone(),
                    passwordSetInput.getVerifyCode(), passwordSetInput.getCountryCode());
            if (!isVerify) {
                throw new BusinessException(PartyCode.VERIFY_CODE_ERROR, "手机号和验证码不匹配");
            }
        }

        Member dbMember = null;
        MemberGroup memberGroup = null;
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        if (null != currentUser) {
            //验证当前登录用户数据
            if (YesNoStatus.YES.getCode().equals(currentUser.getIsMemberGroup())) {
                memberGroup = memberGroupService.get(currentUser.getId());
            } else {
                dbMember = memberService.get(currentUser.getId());
            }
        } else {
            //验证手机号是否存在
            dbMember = memberService.findByLoginNameOld(passwordSetInput.getPhone(), false);

            memberGroup = memberGroupService.findByLoginNameOld(passwordSetInput.getPhone(), false);
        }
        if (null == dbMember && null == memberGroup) {
            throw new BusinessException(PartyCode.CURRENT_USER_DATA_ERROR, "当前用户数据错误,请重新登录");
        }
        if (null != dbMember) {
            dbMember.setPassword(PasswordUtils.encryptPassword(passwordSetInput.getPassword()));
            memberService.update(dbMember);
            redisTokenManager.delRelationshipByKey(dbMember.getId());
        } else if (null != memberGroup) {
            memberGroup.setPassword(PasswordUtils.encryptPassword(passwordSetInput.getPassword()));
            memberGroupService.update(memberGroup);
            redisTokenManager.delRelationshipByKey(memberGroup.getId());
        }
    }

    /**
     * @param passwordSetInput 输入参数
     * @Author yifeng
     * @Description 重置密码
     * @Date 15:31 2019/5/15
     **/
    public void resetPasswordV2(PasswordSetInput passwordSetInput, String identityName) {
        //加短信开关
        boolean isNeedVerify = sysConfigService.isVerifySms();
        if (isNeedVerify) {
            // 验证验证码
            boolean isVerify = memberBizService.verifyCode(passwordSetInput.getPhone(),
                    passwordSetInput.getVerifyCode(), passwordSetInput.getCountryCode());
            if (!isVerify) {
                throw new BusinessException(PartyCode.VERIFY_CODE_ERROR, "手机号和验证码不匹配");
            }
        }
        // 个人身份的
        Member perMember = memberService.findByPhone(passwordSetInput.getPhone(), Constant.MEMBER_PERSONAL);
        // 机构身份
        MemberGroup orgMember = memberGroupService.findByPhone(passwordSetInput.getPhone(), Constant.MEMBER_ORGANIZATION);

        if (null == perMember && orgMember == null) {
            throw new BusinessException(PartyCode.PHONE_EXIST, "账号不存在");
        }

        if (StringUtils.isEmpty(identityName)) {
            throw new BusinessException(PartyCode.MEMBER_UNEXIST, "身份不能为空");
        }

        Member dbMember = null;
        MemberGroup memberGroup = null;

        if (isCopartner.equals(identityName) || isChannelDis.equals(identityName)) {
            dbMember = perMember;
        } else if (isCosponsor.equals(identityName) || "isPartner".equals(identityName)) {
            memberGroup = orgMember;
        }

        if (null == dbMember && null == memberGroup) {
            throw new BusinessException(PartyCode.MEMBER_UNEXIST, "用户不存在");
        }
        if (null != dbMember) {
            dbMember.setPassword(PasswordUtils.encryptPassword(passwordSetInput.getPassword()));
            memberService.update(dbMember);
            redisTokenManager.delRelationshipByKey(dbMember.getId());
        } else {
            memberGroup.setPassword(PasswordUtils.encryptPassword(passwordSetInput.getPassword()));
            memberGroupService.update(memberGroup);
            redisTokenManager.delRelationshipByKey(memberGroup.getId());
        }
    }

    /**
     * @param loginName 手机号
     * @return 身份集合
     * @Author yifeng
     * @Description 根据手机号获取身份
     * @Date 9:57 2019/5/16
     **/
    public List<Map<String, Object>> getIdentityByMobile(String loginName) {
        // 个人身份的
        Member perMember = memberService.findByLoginName(loginName, Constant.MEMBER_PERSONAL);
        // 机构身份
        MemberGroup orgMember = memberGroupService.findByLoginName(loginName, Constant.MEMBER_ORGANIZATION);
        return getMemberIdentities(perMember, orgMember);
    }

    private List<Map<String, Object>> getMemberIdentities(Member perMember, MemberGroup orgMember) {
        List<Map<String, Object>> identities = Lists.newArrayList();
        MemberOutput memberOutput1 = new MemberOutput();
        if (null != perMember) {
            hasCopartnerRole(perMember.getId(), memberOutput1, Constant.MEMBER_PERSONAL);
        }
        if (null != orgMember) {
            hasCopartnerRole(orgMember.getId(), memberOutput1, Constant.MEMBER_ORGANIZATION);
        }

        if (YesNoStatus.YES.getCode().equals(memberOutput1.getIsCopartner())) {
            Map<String, Object> map = Maps.newHashMap();
            map.put("name", "联合发起人");
            map.put("key", isCopartner);
            identities.add(map);
        }

        if (YesNoStatus.YES.getCode().equals(memberOutput1.getIsChannelDis())) {
            Map<String, Object> map = Maps.newHashMap();
            map.put("name", "合伙人");
            map.put("key", isChannelDis);
            identities.add(map);
        }

        if (YesNoStatus.YES.getCode().equals(memberOutput1.getIsCosponsor())) {
            Map<String, Object> map = Maps.newHashMap();
            map.put("name", "合作渠道");
            map.put("key", isCosponsor);
            identities.add(map);
        }
        return identities;
    }
}
